package hse.jack.module;

import hse.jack.model.Account;
import hse.jack.model.SysRoleUser;
import hse.jack.util.DwzUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.service.EntityService;

/**
 * <b>用户信息维护action</b>
 * 
 * @author jack
 * @version 1.0
 * @date 二〇一三年一月二十八日 20:58:51
 * 
 */
@At("/sys")
@IocBean(fields = { "dao" })
public class AccountSysModule extends EntityService<Account> {
	private static final Log log = Logs.get();

	/**
	 * 返回客户端的真实iP地址
	 * 
	 * @param request
	 * @return
	 */
	@At("/ping")
	public String getClientIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		log.debug("request.getHeader(\"x-forwarded-for\")=" + ip);

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
			log.debug("request.getHeader(\"X-Forwarded-For\")=" + ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			log.debug("request.getHeader(\"Proxy-Client-IP\")=" + ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			log.debug("request.getHeader(\"WL-Proxy-Client-IP\")=" + ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
			log.debug("request.getHeader(\"HTTP_CLIENT_IP\")=" + ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			log.debug("request.getHeader(\"HTTP_X_FORWARDED_FOR\")=" + ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			log.debug("request.getRemoteAddr()=" + ip);
		}
		return ip;
	}

	/**
	 * 修改密码
	 * 
	 * @param oldPwd
	 * @param obj
	 * @return
	 */
	@At("/modify")
	public Object modifyPassword(@Param("oldPassword") String oldPwd,
			@Param("..") Account obj) {
		try {
			if (obj != null && Strings.isEmpty(oldPwd)) {
				Account account = this.dao().fetch(
						Account.class,
						Cnd.where("userName", "=", obj.getUserName()).and(
								"password", "=", oldPwd));
				if (account == null) {
					return DwzUtil.dialogAjaxDone(DwzUtil.FAIL, null,
							"输入的原密码错误！");
				}
			}
			this.dao().update(obj);
			return DwzUtil.dialogAjaxDone(DwzUtil.OK, null, "恭喜您密码修改成功，请重新登陆！");
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.debug("E!!!!" + e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}

	}

	/**
	 * 重新登录方法
	 * 
	 * @param obj
	 * @return
	 */
	@At
	public Object reLogin(@Param("..") Account obj) {
		try {
			if (obj != null) {
				Account account = this.dao().fetch(Account.class,
						bulidQureyCnd(obj));
				if (account != null)
					return DwzUtil.dialogAjaxDone(DwzUtil.OK, "", "恭喜您重新登录成功！");
			}
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL, null,
					"您输入的用户名或者密码不正确，请重新输入！");
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.error("E!!!!" + e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}

	}

	/**
	 * 添加角色成功
	 * 
	 * @param roleIds
	 * @param obj
	 * @return
	 */
	@At
	public Object addRole(@Param("roleIds") String roleIds,
			@Param("..") Account obj) {
		try {
			log.debug("-------" + obj.getID());
			this.dao().clear(SysRoleUser.class,
					Cnd.where("user_id", "=", obj.getID()));
			Sql sql = Sqls
					.create("insert into HSE_SYS_ROLE_USER(ROLE_ID,USER_Id) values(@roleID,@userID)");
			if (!Strings.isEmpty(roleIds) && null != obj) {
				String[] roleId = roleIds.split(",");
				for (int i = 0; i < roleId.length; ++i) {
					sql.params().set("roleID", roleId[i]);
					sql.params().set("userID", obj.getID());
					sql.addBatch();
				}
				this.dao().execute(sql);
				return DwzUtil.dialogAjaxDone(DwzUtil.OK, "account", "添加角色成功！");
			}
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL, null, "添加角色失败！");
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.error("E!!!!!" + e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}
	}

	/**
	 * 根据userID来加载menu tree
	 * 
	 * @return
	 */
	@At("/loadMenuByUid")
	@Ok("json")
	public Object loadMenuByUserID() {
		try {
			Account obj = (Account) Mvcs.getHttpSession().getAttribute(
					"account");
			if (obj != null) {
				Sql sql = Sqls
						.create("select distinct m.menuid,m.parent_menu_id,m.menu_text,m.menu_url, m.menu_ord,m.menu_rel from "
								+ "hse_sys_menu m,hse_sys_role_user r,hse_sys_role_permission p "
								+ "where m.menuId=p.menu_id and r.role_id= p.role_id  and r.user_id=@userID "
								+ "order by m.menu_ord");
				sql.params().set("userID", obj.getID());
				sql.setCallback(new SqlCallback() {
					@Override
					public Object invoke(Connection conn, ResultSet rs, Sql sql)
							throws SQLException {
						List<Map<String, String>> menuMap = new ArrayList<Map<String, String>>();
						while (rs.next()) {
							Map<String, String> map = new HashMap<String, String>();
							map.put("id", rs.getString("menuid"));
							map.put("pid", rs.getString("parent_menu_id"));
							map.put("text", rs.getString("menu_text"));
							map.put("url", rs.getString("menu_url"));
							map.put("ord", rs.getString("menu_ord"));
							map.put("rel", rs.getString("menu_rel"));
							map.put("expanded", "true");
							map.put("target", "navTab");
							menuMap.add(map);
						}
						return menuMap;
					}
				});
				this.dao().execute(sql);
				return sql.getList(Map.class);
			}
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL, null, "菜单加载异常");
		} catch (Exception e) {
			if (log.isDebugEnabled())
				log.error("E!!!!" + e);
			return DwzUtil.dialogAjaxDone(DwzUtil.FAIL);
		}
	}

	/**
	 * 构建查询条件
	 * 
	 * @param obj
	 * @return
	 */
	private Cnd bulidQureyCnd(Account obj) {
		Cnd cnd = null;
		if (obj != null) {
			cnd = Cnd.where("1", "=", 1);
			// 按名称查询
			if (!Strings.isEmpty(obj.getUserName()))
				cnd.and("userName", "=", obj.getUserName());
			// 按账套状态查询
			if (!Strings.isEmpty(obj.getPassword()))
				cnd.and("password", "=", obj.getPassword());
		}
		return cnd;
	}
}
